// pages/login/login.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "登录",
    list: [{
      title: "手机号码",
      placeHolder: "请输入手机号码",
      value: "",
      type: 'number',
      edit: false,
      types: "phone"
    }, {
      title: "验证码",
      placeHolder: "请输入手机短信验证码",
      value: "",
      type: 'number',
      code: null,
      edit: false,
      types: "code"
    }],
    time: 120,
    isTimeOut: false
  },
  input_bint_write(e) {
    let {
      index
    } = e.currentTarget.dataset || {},
      list = this.data.list || [], {
        cursor,
        keyCode,
        value
      } = e.detail || {};
    list[index]['value'] = value;
    this.setData({
      list: list
    })
  },
  getCode(e) {
    let {
      index
    } = e.currentTarget.dataset || {}, list = this.data.list || [], that = this;
    let phone = list[0]['value'] || 0;
    if (!wx.$isMobile(phone)) {
      wx.$Toast("手机号码格式不正确");
      return;
    };
    if (this.data.isTimeOut) {
      return;
    }
    that.setTimeout(index, list)
    wx.$api.sendCodes({
      mobile: phone,
      code_type: "xcx_sign"
    }).then(res => {
      console.log("发送验证", res)
    })
  },
  // 倒计时处理
  setTimeout(index, list) {
    let time = this.data.time || 120,
      that = this;
    list[index]['code'] = time + 's';
    that.setData({
      list: list,
      isTimeOut: true
    })
    let T = setInterval(() => {
      time -= 1;
      list[index]['code'] = time + 's';
      if (time <= 0) {
        list[index]['code'] = null;
        clearInterval(T);
        that.setData({
          isTimeOut: false,
          list: list
        })
      } else {
        that.setData({
          isTimeOut: false,
          list: list
        })
      }
    }, 1000)
  },
  toHome() {
    let list = this.data.list || [],
      that = this;
    let mobile = list[0].value || '';
    let v_code = list[1].value || '';
    if (!wx.$isMobile(mobile)) {
      wx.$Toast("手机号码格式不正确");
      return;
    };
    this.saveUserInfo();
    wx.showLoading({
      title: '加载中...',
      mask: true,
      icon: "none"
    })
    wx.$api.verifySms({
      mobile: mobile,
      v_code: v_code,
      code_type: "xcx_sign"
    }).then(res => {
      wx.hideLoading();
      console.log(res, '登录返回')
      let to_page = (url) => {
        wx.reLaunch({
          url: url,
        })
      }
      const toUrl = (is_bind, is_auth, is_contract) => {
        console.log('login_bind_auth_contract', is_bind, is_auth, is_contract);
        if (!is_bind) {
          console.log('is_bind');
          to_page('/pages/login/login');
        } else if (!is_auth) {
          console.log('is_auth');
          to_page('/pages/personalDetails/personalDetails');
        } else if (!is_contract) {
          console.log('is_contract');
          to_page('/pages/newSigned/newSigned');
        } else {
          to_page('/pages/index/index');
        }
      }
      let code = res.data.code,
        data = res.data.data;
      if (code == 200 || code == 208) {
        console.log('login_data', data);
        wx.setStorageSync('is_bind', data.is_bind)
        let is_bind = wx.getStorageSync('is_bind');
        let is_contract = wx.getStorageSync('is_contract');
        let is_auth = wx.getStorageSync('is_auth');
        code == 200 ? toUrl(is_bind, is_auth, is_contract) : toUrl(data.is_bind, data.is_auth, data.is_contract)
      } else {
        wx.$Toast(res.data.msg || '登录错误');
        return;
      }
    })
    // wx.reLaunch({
    //   url: '/pages/index/index',
    // })
  },
  saveUserInfo() {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              var userInfo = res.userInfo
              var nickName = userInfo.nickName
              var avatarUrl = userInfo.avatarUrl
              wx.$api.saveUserInfo({
                head_img: avatarUrl,
                nickname: nickName
              }).then(res => {
                // console.log(res)
              })
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let that = this;
    let token = wx.getStorageSync('token');
    if (!token) {
      await this.getOpenId();
    }
    await this.loginLoad(options);
  },

  loginLoad(options) {
    console.log('come herehere');
    let is_bind = wx.getStorageSync('is_bind');
    let is_auth = wx.getStorageSync('is_auth');
    console.log('is_bind', is_bind, 'is_auth', is_auth);

    console.log('come 2');

    let to_page = (url) => {
      wx.reLaunch({
        url: url,
      })
    }
    console.log('is_bind', is_bind);

    if (is_bind) {
      if (is_auth) { //如果用户已经绑定了手机号，并且已经实名认证了
        if (options.scene != undefined) { //如果带了参数过来，那么就跳到绑定企业页面
          console.log('login_test', options);
          to_page('/pages/newSigned/newSigned?codes=' + options.scene);
        } else { //如果没有带参数的话，那么就去首页
          to_page('/pages/index/index');
        }
      } else { //如果只是没有实名认证的话，就跳转到实名认证页面
        to_page('/pages/personalDetails/personalDetails');
      }
    }

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  async getOpenId() {
    console.log('come 1');
    await getApp().getOpenId();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})